/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.github.florent37.camerafragment.internal.ui.view;

import com.github.florent37.camerafragment.internal.utils.Log;

import ohos.agp.components.AttrSet;
import ohos.agp.components.surfaceprovider.SurfaceProvider;
import ohos.agp.graphics.Surface;
import ohos.agp.graphics.SurfaceOps;
import ohos.agp.render.Canvas;
import ohos.agp.utils.Rect;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 定义SurfaceProvider基类
 *
 * @since 2021-03-23
 */
public class TempSurfaceView extends SurfaceProvider {
    private static final String TAG = "TempSurfaceView";
    private static final String LOG_TAG = "SurfaceHolder";
    private static final boolean IS_DEBUG = false;
    private static final int NEGATIVE = -1;
    private static final int CONSTANT_100 = 100;
    private long mLastLockTime = 0L;
    private int mRequestedWidth = NEGATIVE;
    private int mRequestedHeight = NEGATIVE;
    private boolean isDrawingStopped = true;
    private Surface mSurface = new Surface();
    private ReentrantLock mSurfaceLock = new ReentrantLock();
    private List<SurfaceOps.Callback> mCallbacks = new ArrayList<>();

    /**
     * 构造函数
     *
     * @param context 上下文
     */
    public TempSurfaceView(Context context) {
        this(context, null);
    }

    /**
     * 构造函数
     *
     * @param context 上下文
     * @param attrSet attr集
     */
    public TempSurfaceView(Context context, AttrSet attrSet) {
        this(context, attrSet, "");
    }

    /**
     * 构造函数
     *
     * @param context 上下文
     * @param attrSet attr集
     * @param styleName 类型名字
     */
    public TempSurfaceView(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
    }

    /**
     * SurfaceHolder
     *
     * @since 2021-05-25
     */
    private class SurfaceHolder implements SurfaceOps {
        @Override
        public void addCallback(SurfaceOps.Callback callback) {
            synchronized (mCallbacks) {
                if (!mCallbacks.contains(callback)) {
                    mCallbacks.add(callback);
                }
            }
        }

        @Override
        public void removeCallback(SurfaceOps.Callback callback) {
            synchronized (mCallbacks) {
                mCallbacks.remove(callback);
            }
        }

        @Override
        public void setFormat(int i) {
        }

        @Override
        public Canvas lockCanvas() {
            return internalLockCanvas(null);
        }

        @Override
        public void unlockCanvasAndPost(Canvas canvas) {
            mSurfaceLock.unlock();
        }

        @Override
        public Surface getSurface() {
            return getSurfaceOps().get().getSurface();
        }

        @Override
        public void setFixedSize(int width, int height) {
            if (mRequestedWidth != width || mRequestedHeight != height) {
                mRequestedWidth = width;
                mRequestedHeight = height;
                postLayout();
            }
        }

        @Override
        public void setKeepScreenOn(boolean isKeepOn) {
        }

        @Override
        public Rect getSurfaceDimension() {
            return new Rect();
        }

        private Canvas internalLockCanvas(Rect dirty) {
            mSurfaceLock.lock();
            if (IS_DEBUG) {
                Log.info(TAG, System.identityHashCode(this) + " " + "Locking canvas... stopped="
                    + isDrawingStopped);
            }

            Canvas can = null;
            if (!isDrawingStopped) {
                can = mSurface.acquireCanvas();
            }

            if (IS_DEBUG) {
                Log.info(TAG, System.identityHashCode(this) + " " + "Returned canvas: " + can);
            }
            if (can != null) {
                mLastLockTime = System.currentTimeMillis();
                return can;
            }

            long now = System.currentTimeMillis();
            long nextTime = mLastLockTime + CONSTANT_100;
            if (nextTime > now) {
                try {
                    Thread.sleep(nextTime - now);
                } catch (InterruptedException error) {
                    Log.error(TAG, LOG_TAG + " InterruptedException " + error.getLocalizedMessage());
                }
                now = System.currentTimeMillis();
            }
            mLastLockTime = now;
            mSurfaceLock.unlock();
            return new Canvas();
        }
    }

    /**
     * 获取SurfaceHolder
     *
     * @return SurfaceOps
     */
    public SurfaceOps getHolder() {
        SurfaceHolder surfaceHolder = new SurfaceHolder();
        return surfaceHolder;
    }
}
